/*************************************************************************
	> File Name: client.cpp
	> Author: 
	> Mail: 
	> Created Time: Thu 24 Sep 2020 03:49:43 PM CST
 ************************************************************************/

#include "define.h"

#define DEFAULT_PORT 12000
 
int main(int argc, char** argv){
    int connfd = 0;
    int cLen = 0;
    struct sockaddr_in server;
    if(argc != 2){
        printf("usage: ./client [ipaddress]\n");
        return -1;
    }
    
    server.sin_family = AF_INET;
    server.sin_port = htons(DEFAULT_PORT);
    server.sin_addr.s_addr = inet_addr(argv[1]);
    connfd = socket(AF_INET, SOCK_STREAM, 0);
    if(connfd < 0){
        printf("socket() failure!\n");
        return -1;
    }

    if(connect(connfd, (struct sockaddr*)&server, sizeof(server)) < 0){
        printf("connect() failure!\n");
        return -1;
    }

    Pkg myPkg;
    myPkg.head.num = 1;
    myPkg.head.index = 10001;
    myPkg.content.sex = 'm';
    myPkg.content.score = 990;
    char* temp = "guangzhou and shanghai";
    strncpy(myPkg.content.address, temp, sizeof(myPkg.content.address));
    myPkg.content.age = 18;

    ssize_t  writeLen;
    int tLen = sizeof(myPkg);
    printf("tLen: %d\n", tLen);

    int iLen = 0;
    char pBuff[1024];
    *(int*)(pBuff + iLen) = htonl(tLen);
    iLen += sizeof(int);
    *(int*)(pBuff + iLen) = htonl(myPkg.head.num);
    iLen += sizeof(int);
    *(int*)(pBuff + iLen) = htonl(myPkg.head.index);
    iLen += sizeof(int);
    memcpy(pBuff + iLen, &myPkg.content.sex, sizeof(char));
    iLen += sizeof(char);
    *(int*)(pBuff + iLen) = htonl(myPkg.content.score);
    iLen += sizeof(int);
    memcpy(pBuff + iLen, &myPkg.content.address, sizeof(myPkg.content.address));
    iLen += sizeof(myPkg.content.address);
    *(int*)(pBuff + iLen) = htonl(myPkg.content.age);
    iLen += sizeof(int);

    writeLen = MySend(connfd, pBuff, iLen);
    if(writeLen < 0){
        printf("write failed!\n");
        close(connfd);
        return 0;
    }
    else{
        //这里pbuff是大端序，所以前四位字节分别为 '\0 \0 \0 121'
        printf("write success, writeLen: %d, iLen: %ld, pBuff: %s\n",writeLen, iLen, pBuff);
    }

    close(connfd);
    return 0;

}
